﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;

namespace AyuBookmark.WinForm.Dialogs
{
    /// <summary>
    /// 书签导入/导出对话框
    /// </summary>
    public partial class ImportExportDialog : Form
    {
        private TabControl tabControl;
        private TabPage tabImport;
        private TabPage tabExport;
        private ComboBox cmbImportSource;
        private Button btnImportBrowse;
        private Button btnImport;
        private Button btnExportBrowse;
        private Button btnExport;
        private Button btnCancel;
        private TextBox txtImportFile;
        private TextBox txtExportFile;
        private RadioButton rbExportJson;
        private RadioButton rbExportHtml;
        private ProgressBar progressBar;
        private Label lblStatus;

        public ImportExportDialog()
        {
            InitializeComponent();
            SetupDefaults();
        }

        private void InitializeComponent()
        {
            // 窗体基础设置
            this.SuspendLayout();
            this.Text = "导入/导出书签";
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ClientSize = new Size(500, 350);
            this.Padding = new Padding(10);

            // 选项卡控件
            this.tabControl = new TabControl();
            this.tabControl.Dock = DockStyle.Fill;

            // 导入选项卡
            this.tabImport = new TabPage("导入");
            this.tabImport.Padding = new Padding(10);

            // 导出选项卡
            this.tabExport = new TabPage("导出");
            this.tabExport.Padding = new Padding(10);

            // 导入源选择
            this.cmbImportSource = new ComboBox();
            this.cmbImportSource.DropDownStyle = ComboBoxStyle.DropDownList;
            this.cmbImportSource.Items.AddRange(new object[] {
                "AyuBookmark 备份文件",
                "HTML 书签文件",
                "浏览器导出文件"
            });
            this.cmbImportSource.SelectedIndex = 0;
            this.cmbImportSource.Dock = DockStyle.Top;
            this.cmbImportSource.SelectedIndexChanged += (s, e) => UpdateImportUI();

            // 导入文件路径
            var importFilePanel = new Panel();
            importFilePanel.Dock = DockStyle.Top;
            importFilePanel.Height = 40;

            this.txtImportFile = new TextBox();
            this.txtImportFile.Dock = DockStyle.Fill;
            this.txtImportFile.ReadOnly = true;

            this.btnImportBrowse = new Button();
            this.btnImportBrowse.Text = "浏览...";
            this.btnImportBrowse.Dock = DockStyle.Right;
            this.btnImportBrowse.Width = 80;
            this.btnImportBrowse.Click += (s, e) => BrowseImportFile();

            importFilePanel.Controls.Add(this.txtImportFile);
            importFilePanel.Controls.Add(this.btnImportBrowse);

            // 导入按钮
            this.btnImport = new Button();
            this.btnImport.Text = "开始导入";
            this.btnImport.Dock = DockStyle.Bottom;
            this.btnImport.Height = 40;
            this.btnImport.Click += (s, e) => StartImport();

            // 导出文件路径
            var exportFilePanel = new Panel();
            exportFilePanel.Dock = DockStyle.Top;
            exportFilePanel.Height = 40;

            this.txtExportFile = new TextBox();
            this.txtExportFile.Dock = DockStyle.Fill;

            this.btnExportBrowse = new Button();
            this.btnExportBrowse.Text = "浏览...";
            this.btnExportBrowse.Dock = DockStyle.Right;
            this.btnExportBrowse.Width = 80;
            this.btnExportBrowse.Click += (s, e) => BrowseExportFile();

            exportFilePanel.Controls.Add(this.txtExportFile);
            exportFilePanel.Controls.Add(this.btnExportBrowse);

            // 导出格式选择
            var exportFormatPanel = new Panel();
            exportFormatPanel.Dock = DockStyle.Top;
            exportFormatPanel.Height = 60;

            this.rbExportJson = new RadioButton();
            this.rbExportJson.Text = "JSON 格式（AyuBookmark专用）";
            this.rbExportJson.Checked = true;
            this.rbExportJson.Dock = DockStyle.Top;

            this.rbExportHtml = new RadioButton();
            this.rbExportHtml.Text = "HTML 格式（浏览器兼容）";
            this.rbExportHtml.Dock = DockStyle.Top;

            exportFormatPanel.Controls.Add(this.rbExportHtml);
            exportFormatPanel.Controls.Add(this.rbExportJson);

            // 导出按钮
            this.btnExport = new Button();
            this.btnExport.Text = "开始导出";
            this.btnExport.Dock = DockStyle.Bottom;
            this.btnExport.Height = 40;
            this.btnExport.Click += (s, e) => StartExport();

            // 进度条
            this.progressBar = new ProgressBar();
            this.progressBar.Dock = DockStyle.Bottom;
            this.progressBar.Height = 20;
            this.progressBar.Style = ProgressBarStyle.Continuous;

            // 状态标签
            this.lblStatus = new Label();
            this.lblStatus.Dock = DockStyle.Bottom;
            this.lblStatus.Height = 30;
            this.lblStatus.TextAlign = ContentAlignment.MiddleLeft;

            // 取消按钮
            this.btnCancel = new Button();
            this.btnCancel.Text = "取消";
            this.btnCancel.Dock = DockStyle.Bottom;
            this.btnCancel.Height = 40;
            this.btnCancel.DialogResult = DialogResult.Cancel;

            // 添加控件到导入选项卡
            this.tabImport.Controls.Add(this.btnImport);
            this.tabImport.Controls.Add(this.progressBar);
            this.tabImport.Controls.Add(this.lblStatus);
            this.tabImport.Controls.Add(importFilePanel);
            this.tabImport.Controls.Add(this.cmbImportSource);

            // 添加控件到导出选项卡
            this.tabExport.Controls.Add(this.btnExport);
            this.tabExport.Controls.Add(this.progressBar);
            this.tabExport.Controls.Add(this.lblStatus);
            this.tabExport.Controls.Add(exportFormatPanel);
            this.tabExport.Controls.Add(exportFilePanel);

            // 添加选项卡
            this.tabControl.Controls.Add(this.tabImport);
            this.tabControl.Controls.Add(this.tabExport);

            // 添加主控件
            this.Controls.Add(this.tabControl);
            this.Controls.Add(this.btnCancel);

            this.ResumeLayout(false);
        }

        private void SetupDefaults()
        {
            // 设置默认导出路径
            string exportDir = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                "AyuBookmark Exports");

            if (!Directory.Exists(exportDir))
            {
                Directory.CreateDirectory(exportDir);
            }

            this.txtExportFile.Text = Path.Combine(exportDir,
                $"bookmarks_{DateTime.Now:yyyyMMdd}" +
                (this.rbExportJson.Checked ? ".json" : ".html"));
        }

        private void UpdateImportUI()
        {
            // 根据选择的导入源更新UI
            bool isFileBased = this.cmbImportSource.SelectedIndex != 2;
            this.txtImportFile.Enabled = isFileBased;
            this.btnImportBrowse.Enabled = isFileBased;
        }

        private void BrowseImportFile()
        {
            using (var openDialog = new OpenFileDialog())
            {
                switch (this.cmbImportSource.SelectedIndex)
                {
                    case 0: // AyuBookmark
                        openDialog.Filter = "AyuBookmark备份文件 (*.abk)|*.abk|所有文件 (*.*)|*.*";
                        break;
                    case 1: // HTML
                        openDialog.Filter = "HTML书签文件 (*.html;*.htm)|*.html;*.htm|所有文件 (*.*)|*.*";
                        break;
                }

                if (openDialog.ShowDialog() == DialogResult.OK)
                {
                    this.txtImportFile.Text = openDialog.FileName;
                }
            }
        }

        private void BrowseExportFile()
        {
            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = this.rbExportJson.Checked ?
                    "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*" :
                    "HTML书签文件 (*.html)|*.html|所有文件 (*.*)|*.*";
                saveDialog.FileName = Path.GetFileName(this.txtExportFile.Text);
                saveDialog.InitialDirectory = Path.GetDirectoryName(this.txtExportFile.Text);

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    this.txtExportFile.Text = saveDialog.FileName;
                }
            }
        }

        private void StartImport()
        {
            if (this.cmbImportSource.SelectedIndex < 2 &&
                string.IsNullOrWhiteSpace(this.txtImportFile.Text))
            {
                MessageBox.Show("请选择要导入的文件", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                this.lblStatus.Text = "正在导入...";
                this.progressBar.Value = 0;
                this.btnImport.Enabled = false;

                // 模拟导入过程
                for (int i = 0; i <= 100; i++)
                {
                    this.progressBar.Value = i;
                    System.Threading.Thread.Sleep(20);
                    Application.DoEvents();
                }

                // TODO: 实际导入逻辑
                // var bookmarks = ImportFromFile(this.txtImportFile.Text);

                this.lblStatus.Text = "导入完成！";
                MessageBox.Show("书签导入成功", "完成",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                this.lblStatus.Text = "导入失败";
                MessageBox.Show($"导入过程中出错: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.btnImport.Enabled = true;
            }
        }

        private void StartExport()
        {
            if (string.IsNullOrWhiteSpace(this.txtExportFile.Text))
            {
                MessageBox.Show("请指定导出文件路径", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                this.lblStatus.Text = "正在导出...";
                this.progressBar.Value = 0;
                this.btnExport.Enabled = false;

                // 模拟导出过程
                for (int i = 0; i <= 100; i++)
                {
                    this.progressBar.Value = i;
                    System.Threading.Thread.Sleep(20);
                    Application.DoEvents();
                }

                // TODO: 实际导出逻辑
                // var format = this.rbExportJson.Checked ? ExportFormat.Json : ExportFormat.Html;
                // ExportToFile(this.txtExportFile.Text, format);

                this.lblStatus.Text = "导出完成！";
                MessageBox.Show("书签导出成功", "完成",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                this.lblStatus.Text = "导出失败";
                MessageBox.Show($"导出过程中出错: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.btnExport.Enabled = true;
            }
        }

        public new static DialogResult ShowDialog(IWin32Window owner)
        {
            using (var dialog = new ImportExportDialog())
            {
                return ((Form)dialog).ShowDialog(owner);
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}